package com.trainee.person.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

import com.trainee.person.entity.Person;
import com.trainee.person.util.DBUtil;

public class PersonDao {

	private Connection conn = null;
	PreparedStatement pstmt = null;
	Statement stmt = null;
	ResultSet rs = null;

	public PersonDao() {
		conn = DBUtil.getConnection();
	}

	public long getLatestPersonId() {

		long id = 0;
		String sql = "SELECT MAX(id) as latestId FROM `infoPI` ORDER BY id DESC";
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				id = rs.getInt("latestId");
			}
			return id;

		} catch (SQLException e) {

			e.printStackTrace();
		}

		return id;

	}

	public boolean insertPersonInfo(Person personEntity) throws SQLException {
		boolean flag = false;
		// long id = getLatestPersonId();
		pstmt = (PreparedStatement) conn
				.prepareStatement("INSERT INTO infoPI (name,Designation,company) VALUES(?,?,?)");

		int count = 0;
		pstmt.setString(1, personEntity.getName());
		pstmt.setString(2, personEntity.getDesignation());
		pstmt.setString(3, personEntity.getCompany());

		count = pstmt.executeUpdate();
		if (count > 0) {
			flag = true;
			return flag;
		}
		pstmt.close();
		return flag;

	}

	public void UpdatePersonInfo(Person personEntity) throws SQLException {
		int i = 0;
		pstmt = (PreparedStatement) conn
				.prepareStatement("UPDATE infoPI SET Designation = ? and company = ? WHERE name = ?");
		pstmt.setString(1, personEntity.getName());
		pstmt.setString(2, personEntity.getDesignation());
		pstmt.setString(3, personEntity.getCompany());
		i = pstmt.executeUpdate();
		pstmt.close();

		if (i != 0)
			System.out.println(" Insertion Operation is successfully done."
					+ " & " + "No of record is ,now" + i);

		else
			System.out.println("Record Does Not Exist");

	}

	public boolean getPersonInfo(Person person) {
		System.out.println("Choice 1 called");
		boolean flag = false;
		int count = 0;
		try {
			pstmt = (PreparedStatement) conn
			.prepareStatement("SELECT * FROM infoPI");
			rs=pstmt.executeQuery();
			
			while (rs.next()) {
				String name = rs.getString("name");
				String design = rs.getString("Designation");
				String company = rs.getString("company");
				System.out.println("name = " + name + ", Designation = "
						+ design + ", company = " + company);
				++count;
			}
			if (count > 0) {
				flag = true;
				return flag;
			}
			rs.close();
			stmt.close();
		} catch (SQLException e) {
			Logger.getLogger(e.getMessage());
		}
		return flag;

	}
}
